package com.itheima.server.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.itheima.api.UserApi;
import com.itheima.api.UserInfoApi;
import com.itheima.autoconfig.template.HuanXinTemplate;
import com.itheima.autoconfig.template.SmsTemplate;
import com.itheima.domain.User;
import com.itheima.domain.UserInfo;
import com.itheima.enums.CommentType;
import com.itheima.server.interceptor.UserHolder;
import com.itheima.utils.Constants;
import com.itheima.utils.JwtUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService  {


    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @Resource
    private SmsTemplate smsTemplate;

    @DubboReference
    private UserApi userApi;

    @Resource
    private HuanXinTemplate huanXinTemplate;


    /**
     * 发验证码
     * @param phone
     */
    public void sendMsg(String phone) {
        String code = RandomStringUtils.randomNumeric(6);
//        smsTemplate.sendMsg(phone,code);
        String code2 = "123456";
        redisTemplate.opsForValue().set("CODE_CHECK_" + phone,code2);
        System.out.println("验证码: "+ code2);
    }

    /**
     * 用户登录
     * @param phone
     * @param code
     * @return
     */
    public Map<String,Object> loginVerification(String phone, String code) {
        //到redis中查询code
        String redis = redisTemplate.opsForValue().get("CODE_CHECK_" + phone);
        //校验
        if (StringUtils.isEmpty(code) || !code.equals(redis)){
            throw new RuntimeException("验证码输入错误");
        }
        //根据手机号查询
        User user = userApi.findByMobile(phone);
        boolean isNew = false;
        if (user == null){
            //注册
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long id = userApi.save(user);
            user.setId(id);
            isNew = true;
            
            //新用户要注册到环信中
            String username = "hx"+user.getId();
            String password = Constants.INIT_PASSWORD;
            Boolean create = huanXinTemplate.createUser(username, password);
            if (create){
                user.setHxUser(username);
                user.setHxPassword(password);
                userApi.update(user);
            }
        }
        //生成token
        Map<String,Object> tokenMap = new HashMap<>();
        tokenMap.put("id",user.getId());
        tokenMap.put("mobile",phone);
        String token = JwtUtils.getToken(tokenMap);

        //封装数据
        Map<String,Object> result = new HashMap<>();
        result.put("token",token);
        result.put("isNew",isNew);
        return result;
    }


    /**
     * 校验验证码
     * @param verificationCode
     * @return
     */
    public Boolean checkVerificationCode(String verificationCode) {
        String mobile = UserHolder.getMobile();
        //去redis中拿去
        String redis = redisTemplate.opsForValue().get("CODE_CHECK_" + mobile);
        //校验
        if (StringUtils.isEmpty(verificationCode) || !verificationCode.equals(redis)){
            return false;
        }
        return true;
    }

    /**
     * 修改手机号
     * @param phone
     */
    public void updatePhone(String phone) {
        Long userId = UserHolder.getUserId();
        userApi.update(userId,phone);
    }

}
